﻿using System;
using System.Threading;
using System.Windows.Controls;

namespace Moonwish.Silverlight.OsAvatar.Controls
{
    /// <summary>
    /// 双击按钮，用于桌面实现双击功能。
    /// by zhlin 2012-01-05
    /// </summary>
    public class DblButton : Button
    {
        private bool _isClicked;

        public DblButton()
        {
            Timeout = 700;
        }
        /// <summary>
        /// 双击事件。
        /// </summary>
        public event EventHandler DoubleClick;

        /// <summary>
        /// 重写基类单击事件。
        /// </summary>
        protected override void OnClick()
        {
            lock (this)
            {
                if (_isClicked)
                {
                    _isClicked = false;

                    InvokeDoubleClick();
                }
                else
                {
                    base.OnClick();
                    _isClicked = true;
                    var start = new ParameterizedThreadStart(ResetThread);
                    new Thread(start).Start();
                }
            }
        }

        private void ResetThread(object state)
        {
            Thread.Sleep(Timeout);
            lock (this)
            {
                if (_isClicked)
                {
                    _isClicked = false;
                }
            }
        }

        /// <summary>
        /// 调用双击事件。
        /// </summary>
        void InvokeDoubleClick()
        {
            if (DoubleClick != null)
            {
                DoubleClick(this, new EventArgs());
            }
        }

        /// <summary>
        /// 双击事件距。
        /// </summary>
        public int Timeout { get; set; }
    }
}
